package com.alphaking.util;

import java.io.IOException;
import java.util.UUID;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

public class QiNiuUtil {
	
	// 图片根路径
	public static final String IMAGE_BASE_ACCESS_URL = "http://resources.productshow.cn/";
	public final static String ACCESS_KEY = "CxofRw3rbFocrVJM1BkOb485lCq83-iL-qLZm03M";
	public final static String SECRET_KEY = "7kcCrtW_abnMPSrsuN2u66mIJCHSybPeH1fr2Ta4";
	// 空间名
	public final static String BUCKETNAME = "alphaking";
	
	private static Auth auth = null;

	static {
		if (auth == null) {
			auth = Auth.create(QiNiuUtil.ACCESS_KEY, QiNiuUtil.SECRET_KEY);
		}
	}

	/**
	 * 获取七牛的token
	 * @return
	 */
	public static String getUpToken() {
		return auth.uploadToken(BUCKETNAME);
	}


	/**
	 * 实现将本地的资源存放在七牛资源库
	 * @param filePath
	 * @param key
	 */
	public static void uploadFromServer(String filePath, String key) {
		try {
			Response res = new UploadManager().put(filePath, key, getUpToken());
			System.out.println(res.bodyString());
		} catch (QiniuException e) {
			Response r = e.response;
			System.out.println(r.toString());
			try {
				System.out.println(r.bodyString());
			} catch (QiniuException e1) {
				System.out.println("Exception");
			}
		}
	}

	/**
	 * 直接将二进制流保存到七牛云
	 * @param bytes，文件的二进制流
	 * @throws IOException
	 */
	public static void uploadFromBinary(byte[] bytes,String key) throws IOException{
		 try {
		      //调用put方法上传
		      Response res = new UploadManager().put(bytes, key, getUpToken());
		      //打印返回的信息
		      System.out.println(res.bodyString()); 
		      } catch (QiniuException e) {
		          Response r = e.response;
		          // 请求失败时打印的异常的信息
		          System.out.println(r.toString());
		          try {
		              //响应的文本信息
		            System.out.println(r.bodyString());
		          } catch (QiniuException e1) {
		              //ignore
		          }
		      }       
		
	}
	
	public static void main(String[] args) {
		
	}
	
}
